﻿using IPTVRClient.common;
using IPTVRClient.Utils;
using IPVTRClient.model;
using IPVTRClient.service;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IPVTRClient.views
{
    public partial class VideoReviewForm : Form
    {
        private string pluginPath = Environment.CurrentDirectory + "\\plugins\\";  //vlc插件目录

        private VlcPlayer vlcPlayer = null;

        private VideoReviewService m_VideoRevService = new VideoReviewService();

        private VideoSearchParam param = new VideoSearchParam();

        ILog m_log = LogManager.GetLogger("VideoReviewForm");

        // 记录总数
        private int m_total;

        // 总页数
        private int m_totalpage;

        // 当前页
        private int m_currentpage;

        private int m_start = 0;

        private int m_limit = 10;

        private bool m_IsPlay = true;

        private int m_PlayStartTime = -3;

        private string m_CurSelectFileUrl = "";

        public VideoReviewForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (tbCallingid.Text.Trim().Length > 0)
                {
                    param.Callingdevid = tbCallingid.Text.Trim();
                }

                if (tbcalledid.Text.Trim().Length > 0)
                {
                    param.Calleddevid = tbcalledid.Text.Trim();
                }

                param.Starttime = Global.GetTimeStamp(DateTime.Parse(dtStart.Text));
                param.Endtime = Global.GetTimeStamp(DateTime.Parse(dtEnd.Text));

                DataSet tmpdataset = m_VideoRevService.GetVideo(param, 0, 10);
                List<VideoInfo> videoList = Global.TableToEntity<VideoInfo>(tmpdataset.Tables[0]);

                List<VideoInfoExt> videoExtList = new List<VideoInfoExt>();
                foreach (VideoInfo vinfo in videoList)
                {
                    VideoInfoExt videoext = new VideoInfoExt(vinfo);

                    videoext.Timestr = Global.ConvertIntDatetime(videoext.Time);
                    videoExtList.Add(videoext);
                }
                dgvFile.DataSource = videoExtList;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VideoReviewForm_Load(object sender, EventArgs e)
        {
            initTotalAndPage();
            m_currentpage = 1;
            initData(m_start, m_limit);
            lblCurrent.Text = "共" + m_totalpage.ToString() + "页，当前第" + m_currentpage.ToString() + "页";
        }

        /// <summary>
        /// 初始化总数和页数
        /// </summary>
        private void initTotalAndPage()
        {
            // 查询总数
            m_total = m_VideoRevService.GetRecordeCount(param);

            // 计算总页数
            m_totalpage = m_total / m_limit;

            if (m_total % m_limit > 0)
            {
                m_totalpage++;
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void initData(int start, int limit)
        {
            try
            {
                DataSet tmpdataset = m_VideoRevService.GetAllVideo(start, limit);
                List<VideoInfo> videoList = Global.TableToEntity<VideoInfo>(tmpdataset.Tables[0]);
                List<VideoInfoExt> videoExtList = new List<VideoInfoExt>();
                foreach (VideoInfo vinfo in videoList)
                {
                    VideoInfoExt videoext = new VideoInfoExt(vinfo);

                    videoext.Timestr = Global.ConvertIntDatetime(videoext.Time);
                    videoExtList.Add(videoext);
                }

                dgvFile.DataSource = videoExtList;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 播放按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int a = dgvFile.CurrentRow.Index;
                m_CurSelectFileUrl = dgvFile.Rows[a].Cells["playurl"].Value.ToString();
                if (vlcPlayer == null)
                {
                    vlcPlayer = new VlcPlayer(pluginPath, "");
                    vlcPlayer.SetRenderWindow((int)plMain.Handle);
                }
                else
                {
                    vlcPlayer.Stop();

                    btnPause.Text = "暂停";
                    m_IsPlay = true;
                }

                if (m_CurSelectFileUrl.IndexOf("http://") != -1 || m_CurSelectFileUrl.IndexOf("HTTP://") != -1)
                {
                    vlcPlayer.LoadOnlineFile(m_CurSelectFileUrl);
                }
                else
                {
                    m_CurSelectFileUrl = m_CurSelectFileUrl.Replace("/", "\\");
                    vlcPlayer.LoadFile(m_CurSelectFileUrl);
                }

                this.PlayStatustimer.Enabled = true;
                m_PlayStartTime = 0;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 列渲染
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvFile_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == dgvFile.Columns["time"].Index)
                {
                    if (e.Value.ToString().Trim() != "" && e.Value != null)
                    {
                        DateTime dt = Global.GetDateTime(e.Value.ToString().Trim());
                        e.Value = dt.ToString();
                    }
                }

                // 表格美化
                dgvFile.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            try
            {
                tbCallingid.Text = "";
                tbcalledid.Text = "";
                dtStart.Text = "";
                dtEnd.Text = "";
                param = null;
                DataSet tmpdataset = m_VideoRevService.GetAllVideo(0, 10);
                List<VideoInfo> videoList = Global.TableToEntity<VideoInfo>(tmpdataset.Tables[0]);

                dgvFile.DataSource = videoList;
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                // 如果当前登陆用户不是管理用户
                if (Global.CurrentUser.UserLevel != 1)
                {
                    Global.showAlertBox("对不起，普通用户不能删除文件，请联系高级管理员！");
                    return;
                }

                if (dgvFile.SelectedRows.Count == 0)
                {
                    Global.showAlertBox("请选择要删除的用户");
                    return;
                }

                //int a = dgvFile.CurrentRow.Index;

                DialogResult result = Global.showQuestionMessageBox("确定要删除该记录吗", 2);
                if (result == DialogResult.OK)
                {
                    long id = Convert.ToInt64(dgvFile.SelectedRows[0].Cells[0].Value.ToString());
                    int t = m_VideoRevService.DeleteCallRecordById(id);

                    if (t > 0)
                    {
                        DataSet tmpdataset = m_VideoRevService.GetVideo(param, 0, 10);
                        List<VideoInfo> videoList = Global.TableToEntity<VideoInfo>(tmpdataset.Tables[0]);

                        dgvFile.DataSource = videoList;
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("删除回放文件异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblPre_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                initTotalAndPage();
                if (m_currentpage > 1)
                {
                    m_currentpage--;
                    initData((m_currentpage - 1) * m_limit, m_limit);
                    lblCurrent.Text = "共" + m_totalpage.ToString() + "页，当前第" + m_currentpage.ToString() + "页";
                }
                else if (1 == m_currentpage)
                {
                    Global.showAlertBox("已经是第一页了!");
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblNext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                initTotalAndPage();
                if (m_currentpage < m_totalpage)
                {
                    initData(m_currentpage * m_limit, m_limit);
                    m_currentpage++;
                    lblCurrent.Text = "共" + m_totalpage.ToString() + "页，当前第" + m_currentpage.ToString() + "页";
                }
                else
                {
                    Global.showAlertBox("已经是最后一页了!");
                }
            }
            catch(Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblFirst_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                initTotalAndPage();
                if (m_currentpage == 1)
                {
                    Global.showAlertBox("已经是首页了!");
                    return;
                }
                else
                {
                    initData(0, m_limit);
                    m_currentpage = 1;
                    lblCurrent.Text = "共" + m_totalpage.ToString() + "页，当前第" + m_currentpage.ToString() + "页";
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblEnd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                initTotalAndPage();
                if (m_currentpage == m_totalpage)
                {
                    Global.showAlertBox("已经是尾页了!");
                    return;
                }
                else
                {
                    initData((m_totalpage - 1) * m_limit, m_limit);
                    m_currentpage = m_totalpage;
                    lblCurrent.Text = "共" + m_totalpage.ToString() + "页，当前第" + m_currentpage.ToString() + "页";
                }
            }
            catch (Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 暂停播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPause_Click(object sender, EventArgs e)
        {
            try
            {
                if (null != vlcPlayer)
                {
                    if (m_IsPlay)
                    {
                        vlcPlayer.Pause();
                        btnPause.Text = "播放";
                        m_IsPlay = false;
                        this.PlayStatustimer.Enabled = false;
                    }
                    else
                    {
                        vlcPlayer.Play();
                        btnPause.Text = "暂停";
                        m_IsPlay = true;
                        this.PlayStatustimer.Enabled = true;
                    }
                }
            }
            catch(Exception ex)
            {
                m_log.Error("操作异常，操作信息：" + ex.Message);
            }
        }

        private void VideoReviewForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (vlcPlayer != null)
            {
                vlcPlayer.Stop();
            }

            btnPause.Text = "播放";
            m_IsPlay = false;
            this.PlayStatustimer.Enabled = false;
        }

        private void PlayStatustimer_Tick(object sender, EventArgs e)
        {
            if (vlcPlayer != null && !vlcPlayer.IsPlaying(m_PlayStartTime))
            {
                vlcPlayer.Stop();
                if (m_CurSelectFileUrl.IndexOf("http://") != -1 || m_CurSelectFileUrl.IndexOf("HTTP://") != -1)
                {
                    vlcPlayer.LoadOnlineFile(m_CurSelectFileUrl);
                }
                else
                {
                    vlcPlayer.LoadFile(m_CurSelectFileUrl);
                }
                Thread.Sleep(500);
                vlcPlayer.Pause();
                btnPause.Text = "播放";
                m_IsPlay = false;
                this.PlayStatustimer.Enabled = false;
                m_PlayStartTime = -3;
            }
            else
            {

                m_PlayStartTime += 1;
            }
            
        }
    }
}
